<template>
  <div class="comments app-container">
    <nav-bar title="评论" left-arrow fixed placeholder />

    <comments :style="ScrollStyle"
              :top-comments="topComments"
              :hot-comments="hotComments"
              :comments="comments"
              :more="more"
              @init="_initScroll(true)"
              @pullUp="getData(false)"
              ref="comments" />
  </div>
</template>

<script>
import { CommentMusicAsync } from 'api/song'
import { CommentPlayListAsync } from 'api/playlist'
import comments from './comments'

export default {
  name: 'comments-index',
  data () {
    return {
      topComments: [],
      hotComments: [],
      comments: [],
      loading: false,
      error: false,
      limit: 20,
      page: 0,
      more: true
    }
  },
  created () {
    if (!this.$route.query.id) this.$router.back()
    window.index = this
  },
  methods: {
    _initScroll () {
      if (this.$refs.comments) {
        this.$refs.comments.$refs.scroll && this.$refs.comments.$refs.scroll.autoPullUpLoad()
      }
    },
    async getData (state = true) {
      const Search = { id: this.id, offset: this.offset, limit: this.limit }

      try {
        let Data = { hotComments: [], topComments: [], comments: [], more: false }
        switch (this.type) {
          case 1:
            Data = await CommentMusicAsync(Search)
            break
          case 2:
            Data = await CommentPlayListAsync(Search)
            break
        }

        this.page++
        if (Data.hotComments) this.hotComments = Data.hotComments
        if (Data.hotComments) this.topComments = this.topComments.concat(Data.topComments)
        this.comments = this.comments.concat(Data.comments)

        if (Data.more) {
          this.$refs.comments && this.$refs.comments.finish()
        } else {
          this.more = false
        }
      } catch (err) {
        this.$refs.comments && this.$refs.comments.finish()
      }
    }
  },
  computed: {
    /**
     * 评论类型
     * 1 歌曲
     * 2 歌单
     */
    type () {
      return parseInt(this.$route.query.type) || null
    },
    id () {
      return parseInt(this.$route.query.id) || null
    },
    offset () {
      return this.page * this.limit
    },
    ScrollStyle () {
      return {
        top: this.$store.state.StatusBarHeight + this.$config.nav_bar_height + 'px'
      }
    }
  },
  components: { comments }
}
</script>
